function timeFunction( callback ) {
	//Time how long things take
	var now = new Date();
	var startTicks = now.getTime();
	
	callback();
	
	now = new Date();
	var endTicks = now.getTime();
	
	console.log('took ' + (endTicks-startTicks) + 'ms.');
}

/* This is only appropriate locally, it will not work in the repo. It will create a link to each missing image */
function getMissingImages() {
	$('img').each(function() {
			$(this)
			.error(function() {
				$( document.createElement('a') ).attr({
	                href: this.src.replace('localhost:81/tk','hyperiums.com'),
	                target: '_blank'
	            })
	            .css('display','block')
	            .html(this.src.replace('localhost:81/tk','hyperiums.com'))
	            .appendTo(document.body)	
			})
			.attr('src', this.src)
		;
	})
}

function setCookie(c_name,value,exdays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++) {
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name) {
			return unescape(y);
		}
	}
}

function getCaller(evt) {
	return ( evt.target || evt.srcElement );
}

function getIntFromAvgp(avgp) {
	if(avgp.match("([0-9.]+)K")) {
		return avgp.match("([0-9.]+)K")[1]*1000;
	}
	if(avgp.match("([0-9.]+)M")) {
		return avgp.match("([0-9.]+)M")[1]*1000000;
	}
	if(avgp.match("([0-9.]+)B")) {
		return avgp.match("([0-9.]+)B")[1]*1000000000;
	}
	return avgp;
}

function getAvgpFromInt(avgp) {
	if(avgp >= 1000000000) {
		return Math.round(avgp/100000000)/10+'B';
	} else if(avgp >= 1000000) {
		return Math.round(avgp/100000)/10+'M';
	} else if(avgp >= 1000) {
		return Math.round(avgp/100)/10+'K';
	}
	return avgp;
}

function makeid() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}


include("http://www.google.com/recaptcha/api/js/recaptcha_ajax.js");
function captchaAwareAjax(options) {
	if( !updateAjaxCounter(1) ) {
		alert('Blocking request to prevent 5 minute ban');
		return;
	}

	$.ajax(options).always(function(xhr, statusText) {
		detectCaptcha(xhr);
	})
}

function updateAjaxCounter(modifier) {
	/*var ajaxCount = getCookie('ajaxCount');
	var maxAjax = 60;
	
	if( typeof ajaxCount == 'undefined' )
		ajaxCount = 0;
	else
		ajaxCount = ajaxCount*1; //force int
		
	ajaxCount = ajaxCount+modifier;
	
	if( ajaxCount > maxAjax && modifier > 0 ) {
		console.log(ajaxCount);
		return false;
	}
		
	if( ajaxCount <= 0 ) {
		if( window.ajaxCounter ) window.ajaxCounter.remove();
		
		setCookie('ajaxCount', 0);
		
		return true;
	} else {
		if( !window.ajaxCounter ) {
			window.ajaxCounter = $('<div></div>').css({
				position: 'fixed',
				color: '#FF0000',
				top : 10,
				left : 10,
				width: '40px',
				height: '20px',
				border: '1px solid #999999',
				background: '#000',
				padding: '10px',
				textAlign: 'center'
			}).appendTo( document.body );
		}
		
		window.ajaxCounter.html( ajaxCount + '/' + maxAjax );
		
		setCookie('ajaxCount', ajaxCount);
		
		return true;
	}*/
	return true;
}

setInterval(function(){updateAjaxCounter(-1);}, 3000);

function detectCaptcha(text) {
	var findCaptcha = text.match(/[^"]*api.recaptcha[^"]*/)
	if( findCaptcha ) {
		alert("Caution: Captcha Detected!");
		var botcheckident = text.match(/name=botcheckid value=[0-9]{1,}/)[0].replace(/[^0-9]*/g,'');

		openCaptchaModal( botcheckident );
	}
}

function openCaptchaModal(botcheckident) {
	var uid = makeid();
	
	var container = $( document.createElement('div') )
		.addClass('captchaModal')
		.appendTo( document.body )
	;
	
	var theForm = $( document.createElement('form') )
		.attr({
			method : "POST",
			action : "Home"
		})
		.appendTo( container )
	;
	
	$( document.createElement('input') )
		.attr({
			type:"hidden",
			name: "botcheckid"
		})
		.val(botcheckident)
		.appendTo(theForm)
	;
	
	$( document.createElement('div') )
		.attr({
			id : 'captchadiv'+uid
		})
		.appendTo( theForm )
	;
	
	$( document.createElement('input') )
		.attr({
			name : "captcha",
			value: "I am not a robot!",
			type: "hidden"
		})
		.appendTo( theForm )
	;
	
	
	
    Recaptcha.create("6Lf7tt0SAAAAAKPwVQuKkutH-cEVzewOkEXKRwSM", 'captchadiv'+uid, {
        tabindex: 1,
        theme: "red",
        callback: Recaptcha.focus_response_field,
        theme:"blackglass"
    });
	
	$( document.createElement('input') )
		.attr({
			type: "submit"
		})
		.addClass('submitButton')
		.val("I am not a robot!")
		.appendTo(theForm)
		.click(function(e) {
			captchaAwareAjax({
				url : theForm.attr('action'),
				type : "POST",
				data : theForm.serialize(),
				success : function() {
					container.remove();
				}
			});
			
			e.preventDefault();
		})
	;	
}